package com.swipemaster.network.task;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;

import com.swipemaster.R;
import com.swipemaster.common.Global;

/** Enhances AsyncTask with ProgressDialog. Make sure to call super.onPostExecute(). */
abstract class ProgressTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result>
{
	protected final Activity activity;
	protected final ProgressDialog progressDialog;

	public ProgressTask(Activity activity)
	{
		this.activity = activity;
		this.progressDialog = new ProgressDialog(activity);
		this.progressDialog.setOnCancelListener(new OnCancelListener()
		{
			@Override
			public void onCancel(DialogInterface dialog)
			{
				ProgressTask.this.cancel(true);
			}
		});
	}

	@Override
	protected void onPostExecute(Result result)
	{
		if (progressDialog.isShowing() && !activity.isFinishing())
		{
			progressDialog.dismiss();
		}
	}

	@Override
	protected void onPreExecute()
	{
		if (!activity.isFinishing())
		{
			progressDialog.setMessage(Global.app.getString(R.string.wait));
			progressDialog.show();
		}
	}
}
